package com.quick.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.quick.base.KeyValue;
import com.quick.base.Page;
import com.quick.base.Search;
import com.quick.mapper.SysDictMapper;
import com.quick.service.ISysDictService;
import com.quick.sys.domain.dto.SysDictDTO;
import com.quick.sys.domain.pojo.SysDict;
import com.quick.sys.domain.search.SysDictSearch;
import com.quick.sys.domain.vo.SysDictVo;
import com.quick.util.Convert;
import com.quick.util.PageUtil;
import com.quick.util.QuickTool;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class SysDictServiceImpl implements ISysDictService {

	private final SysDictMapper sysDictMapper;

	@Override
	public Boolean saveDict(SysDictDTO dict) {
		SysDict entity = Convert.convert(dict, SysDict.class);
		entity.setLabelValue(JSONArray.toJSONString(dict.getValue()));
		if (QuickTool.isNull(dict.getId())) {
			QuickTool.setFillInsert(entity);
			return sysDictMapper.insert(entity) > 0;
		}
		QuickTool.setFillUpdate(entity);
		return sysDictMapper.updateById(entity) > 0;
	}

	@Override
	public Page<SysDictVo> searchDict(Search<SysDictSearch> search) {
		PageHelper.startPage(search.getPageNum(), search.getPageSize());
		QueryWrapper<SysDict> queryWrapper = new QueryWrapper<SysDict>();
		queryWrapper(queryWrapper, search.getSearch());
		List<SysDict> dicts = sysDictMapper.selectList(queryWrapper);
		PageInfo<SysDict> pageInfo = new PageInfo<>(dicts);
		return PageUtil.page(pageInfo, SysDictVo.class);
	}

	@Override
	public SysDictVo queryDict(Integer id) {
		SysDict original = sysDictMapper.selectById(id);
		return Convert.convert(original, SysDictVo.class);
	}

	@Override
	public Boolean delDict(Integer id) {
		return sysDictMapper.deleteById(id)>0;
	}

	@Override
	public Map<String, List<KeyValue>> all() {
		QueryWrapper<SysDict> wrapper = new QueryWrapper<SysDict>();
		List<SysDict> dicts = sysDictMapper.selectList(wrapper);
		Map<String, List<KeyValue>> res = new HashMap<String, List<KeyValue>>();
		for (SysDict ele : dicts) {
			List<KeyValue> array = JSON.parseArray(ele.getLabelValue(),KeyValue.class);
			res.put(ele.getDictType(), array);
		}
		return res;
	}

}
